<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>Zookeeper Watcher机制 | flyingzc's blog</title><meta name="author" content="flyingzc"><meta name="copyright" content="flyingzc"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="watcher流程三个过程:client 注册 Watcherserver 处理 Watcherclient 回调 Watcher client 注册 Watcherzk client 可以通过 new ZooKeeper(),getData(),getChildren(), exist() 传入 watcher对象 来 注册 Watcher. 比如对于 getData()时注册watcher的操">
<meta property="og:type" content="article">
<meta property="og:title" content="Zookeeper Watcher机制">
<meta property="og:url" content="https://flyingzc.github.io/articles/zk/zk08_watcher.html">
<meta property="og:site_name" content="flyingzc&#39;s blog">
<meta property="og:description" content="watcher流程三个过程:client 注册 Watcherserver 处理 Watcherclient 回调 Watcher client 注册 Watcherzk client 可以通过 new ZooKeeper(),getData(),getChildren(), exist() 传入 watcher对象 来 注册 Watcher. 比如对于 getData()时注册watcher的操">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://flyingzc.github.io/images/zc-icon.jpeg">
<meta property="article:published_time" content="2019-12-13T16:00:00.000Z">
<meta property="article:modified_time" content="2025-01-21T01:51:41.217Z">
<meta property="article:author" content="flyingzc">
<meta property="article:tag" content="Zookeeper">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://flyingzc.github.io/images/zc-icon.jpeg"><script type="application/ld+json">{
  "@context": "https://schema.org",
  "@type": "BlogPosting",
  "headline": "Zookeeper Watcher机制",
  "url": "https://flyingzc.github.io/articles/zk/zk08_watcher.html",
  "image": "https://flyingzc.github.io/images/zc-icon.jpeg",
  "datePublished": "2019-12-13T16:00:00.000Z",
  "dateModified": "2025-01-21T01:51:41.217Z",
  "author": [
    {
      "@type": "Person",
      "name": "flyingzc",
      "url": "https://flyingzc.github.io/"
    }
  ]
}</script><link rel="shortcut icon" href="/images/zc-icon.jpeg"><link rel="canonical" href="https://flyingzc.github.io/articles/zk/zk08_watcher.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta name="google-site-verification" content="DentpX3LnP_WNgEeFnNIcTZZky-Bby-zL-uI_9GqTAw"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css"><script>
    (() => {
      
    const saveToLocal = {
      set: (key, value, ttl) => {
        if (!ttl) return
        const expiry = Date.now() + ttl * 86400000
        localStorage.setItem(key, JSON.stringify({ value, expiry }))
      },
      get: key => {
        const itemStr = localStorage.getItem(key)
        if (!itemStr) return undefined
        const { value, expiry } = JSON.parse(itemStr)
        if (Date.now() > expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return value
      }
    }

    window.btf = {
      saveToLocal,
      getScript: (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        Object.entries(attr).forEach(([key, val]) => script.setAttribute(key, val))
        script.onload = script.onreadystatechange = () => {
          if (!script.readyState || /loaded|complete/.test(script.readyState)) resolve()
        }
        script.onerror = reject
        document.head.appendChild(script)
      }),
      getCSS: (url, id) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onload = link.onreadystatechange = () => {
          if (!link.readyState || /loaded|complete/.test(link.readyState)) resolve()
        }
        link.onerror = reject
        document.head.appendChild(link)
      }),
      addGlobalFn: (key, fn, name = false, parent = window) => {
        if (!false && key.startsWith('pjax')) return
        const globalFn = parent.globalFn || {}
        globalFn[key] = globalFn[key] || {}
        globalFn[key][name || Object.keys(globalFn[key]).length] = fn
        parent.globalFn = globalFn
      }
    }
  
      
      const activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      const activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }

      btf.activateDarkMode = activateDarkMode
      btf.activateLightMode = activateLightMode

      const theme = saveToLocal.get('theme')
    
          theme === 'dark' ? activateDarkMode() : theme === 'light' ? activateLightMode() : null
        
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        document.documentElement.classList.toggle('hide-aside', asideStatus === 'hide')
      }
    
      
    const detectApple = () => {
      if (/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)) {
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
  
    })()
  </script><script async="async" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><script>(adsbygoogle = window.adsbygoogle || []).push({
  google_ad_client: '',
  enable_page_level_ads: 'true'
});</script><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false,"highlightFullpage":false,"highlightMacStyle":false},
  copy: {
    success: '复制成功',
    error: '复制失败',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'null',
  Snackbar: undefined,
  infinitegrid: {
    js: 'https://cdn.jsdelivr.net/npm/@egjs/infinitegrid/dist/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyloadPlugin: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Zookeeper Watcher机制',
  isHighlightShrink: false,
  isToc: true,
  pageType: 'post'
}</script><link rel="stylesheet" href="/self/github-dark.css"><meta name="generator" content="Hexo 7.0.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img text-center"><img src="/images/zc-icon.jpeg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data text-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">84</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">36</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">29</div></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header"><nav id="nav"><span id="blog-info"><a class="nav-site-title" href="/"><span class="site-name">flyingzc's blog</span></a><a class="nav-page-title" href="/"><span class="site-name">Zookeeper Watcher机制</span></a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div><div id="toggle-menu"><span class="site-page"><i class="fas fa-bars fa-fw"></i></span></div></div></nav><div id="post-info"><h1 class="post-title">Zookeeper Watcher机制</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2019-12-13T16:00:00.000Z" title="发表于 2019-12-14 00:00:00">2019-12-14</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2025-01-21T01:51:41.217Z" title="更新于 2025-01-21 09:51:41">2025-01-21</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Zookeeper/">Zookeeper</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title=""><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">浏览量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="container post-content" id="article-container"><h1 id="watcher流程"><a href="#watcher流程" class="headerlink" title="watcher流程"></a>watcher流程</h1><p>三个过程:<br>client 注册 Watcher<br>server 处理 Watcher<br>client 回调 Watcher</p>
<h2 id="client-注册-Watcher"><a href="#client-注册-Watcher" class="headerlink" title="client 注册 Watcher"></a>client 注册 Watcher</h2><p>zk client 可以通过 new ZooKeeper(),getData(),getChildren(), exist() 传入 watcher对象 来 注册 Watcher.</p>
<p>比如对于 <code>getData()时注册watcher的操作</code>.实际上 client 就是把 watcher 对象 存到 DataWatchRegistration 里,再创建 Packet,存入 outgoingQueue,等待 SendThread 线程取出来发给 server.</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><code class="hljs plaintext">// 1.创建ZooKeeper对象时注册Watcher<br>- new ZooKeeper()传入Watcher,会回调Watcher.process()方法<br>    - ZooKeeper中会创建ZKWatchManager<br>    - watchManager.defaultWatcher = watcher;初始化默认Watcher<br>    - 解析connectString创建hostProvider<br>    - 创建客户端连接管理类ClientCnxn<br>    - 启动ClientCnxn线程<br>        - ClientCnxn构造方法中创建sendThread和eventThread<br>            EventThread负责处理Server返回的WatchedEvent,回调注册的客户端事件接口处理函数<br>            SendThread为outgoing(传出)请求队列提供服务并生成心跳.它还会产生ReadThread<br><br>// 2.setData()<br>- zk.setData(path, data, version);<br>    - 创建RequestHeader,调用cnxn.submitRequest(h, request, response, null);<br>        - clientCnxn.submitRequest()中:将Request等信息封装成packet,放入outgoingQueue队列中<br><br>// sendThread逻辑<br>- ClientCnxn.SendThread中<br>    - run()逻辑<br>        - 建立与server的连接<br>        - 定时发送ping<br>        - 委托给 clientCnxnSocket.doTransport()进行底层的nio传输<br>            - ClientCnxnSocketNIO.doIO()中<br>                从outgoingQueue取出packet<br>            - p.createBB();// 序列化<br>            - sock.write(p.bb);// 发送<br>            - 从outgoingQueue队列中移除该发送的包<br>            - pendingQueue.add(p);// 将packet加入到pendingQueue队列<br><br>// 3.getData()时注册watcher<br>- zk.getData(zooDataPath, watcher, stat);getData()时注册watcher<br>    - wcb = new DataWatchRegistration(watcher, clientPath); // 注册 watcher到DataWatchRegistration中<br>        - packet = new Packet(h, r, request, response, watchRegistration);通过watchRegistration创建packet,存入outgoingQueue,等待发送<br></code></pre></td></tr></table></figure>

<h2 id="server-处理-Watcher"><a href="#server-处理-Watcher" class="headerlink" title="server 处理 Watcher"></a>server 处理 Watcher</h2><p>比如对于 getData()时注册watcher的处理:其实 server端就是在 FinalRequestProcessor 中将 Watcher(其实是NIOServerCnxn对象) 添加到 WatchManager 对象的 watchTable 和 watch2Paths 属性中.</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs plaintext">- 2.Server处理Watcher<br>    - 处理客户端发来的zk.getData()注册watcher的请求<br>        - NIOServerCnxnFactory.run()有读写事件<br>            - NIOServerCnxn.doIO()<br>                - NIOServerCnxn.readPayload();// 读取内容<br>                    - NIOServerCnxn.readRequest()<br>                        - ZooKeeperServer.processPacket()<br>                            - ZooKeeperServer.submitRequest(si);// 提交请求<br>                                - touch(si.cnxn);// 判断session是否存在或者已经超时<br>                                - firstProcessor.processRequest(si);// 处理请求<br>                                    - Processor链处理...<br>                                        - FinalRequestProcessor.processRequest()中<br>                                            - case OpCode.getData:// 对于获取数据请求,若有watch会注册<br>                                                - dataWatches.addWatch(path, watcher);// 若有watcher的话则注册watcher,此时watcher为NIOServerCnxn.将Watcher添加到WatchManager对象的watchTable和watch2Paths属性中<br></code></pre></td></tr></table></figure>

<p>当server端收到了client端的setData()请求,由于引起了数据变更,会触发  getData()时注册watcher. 其实就是从上面 getData() 时存入的 watchTable 里查出来 watchers 并移除(只触发一次),调用 watcher.process()方法,也就是 NIOServerCnxn.process() 发送给 客户端 Watcher事件.</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs plaintext">- 3.Server触发Watcher<br>    - 处理client发来的zk.setData()请求<br>        - FinalRequestProcessor.processRequest()中<br>            - rc = zks.processTxn(hdr, txn);// 处理事务,应用到 dataTree上<br>                - DataTree.setData()中,有watcher时会触发watcher<br>                    - dataWatches.triggerWatch(path, EventType.NodeDataChanged); // setData()时会导致数据变更,若有watcher会触发watcher<br>                        - watchers = watchTable.remove(path); // 获取该path对应的watchers,watchers只触发一次就移除<br>                        - w.process(e);// 进行watcher事件处理,传入WatchedEvent,此时的w是NioServerCnxn对象<br>                            - NIOServerCnxn.process()中,创建响应头,xid=-1代表watcher事件.将WatchedEvent对象转换为WatcherEvent,用于网络传输,响应客户端<br></code></pre></td></tr></table></figure>

<h2 id="client-回调-Watcher"><a href="#client-回调-Watcher" class="headerlink" title="client 回调 Watcher"></a>client 回调 Watcher</h2><p>client端 通过 SendThread.readResponse() 接收服务端响应.</p>
<p>根据 replyHdr.xid 判断是 Watcher事件.</p>
<p>将 来自服务端的响应,反序列成 WatcherEvent 对象,WatcherEvent 的信息里只包含 type,state,path 信息.<br><img src="https://gitee.com/flyingzc/MyImg/raw/master/img/zk/client%E6%94%B6%E5%88%B0%E7%9A%84watcher%E4%BF%A1%E6%81%AF.png" alt="client端收到的server端的watcher信息"></p>
<p>然后再将 WatcherEvent 对象 转成 WatchedEvent 对象.<br><img src="https://gitee.com/flyingzc/MyImg/raw/master/img/zk/client%E9%80%9A%E8%BF%87watcher%E5%88%9B%E5%BB%BAWatchedEvent%E5%AF%B9%E8%B1%A1.png" alt="根据watcher信息创建的WatchedEvent对象"></p>
<p>从 ZKWatchManager.dataWatches 中 取出 path 对应的 watcher 并移除(只触发一次),连同 WatchedEvent 创建WatcherSetEventPair 对象.入 waitingEvents 队列,交给 eventThread 线程处理.</p>
<p>eventThread线程 从 waitingEvents 队列里取出对应的 watcher,调用 watcher.process() 处理.</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs plaintext">- 4.Client回调Watcher<br>    - SendThread.readResponse()接收服务端响应<br>        - 根据replyHdr.getXid() == -1 判断是Watcher通知,反序列化出WatcherEvent对象<br>        - eventThread.queueEvent(we);// 将Watcher事件 入事件队列,交给EventThread处理<br>            - watcher.materialize()根据watcher的事件类型进行不同的处理<br>                - 比如NodeDataChanged和NodeCreated事件<br>                - 1.从 ZKWatchManager.dataWatches 中移除 clientPath 对应的 watchers(相当于只能触发一次),并将这些移除的 watchers 添加到 result 中返回<br>            - 通过watcher和event创建WatcherSetEventPair<br>            - waitingEvents.add(pair);// 将WatcherSetEventPair对象入waitingEvents这个LinkedBlockingQueue中(保证watcher顺序)<br>    - EventThread.run()中<br>        - 从waitingEvents中取出event,调processEvent(event)<br>            - processEvent(event)中<br>                - event中包含实际的watcher对象,直接回调watcher.process()即可<br></code></pre></td></tr></table></figure>

<h1 id="相关类"><a href="#相关类" class="headerlink" title="相关类"></a>相关类</h1><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs plaintext">Watcher<br>WatchedEvent<br><br>ZooKeeper<br>ZKWatchManager<br><br>ClientWatchManager<br><br>WatchRegistration<br>    ChildWatchRegistration<br>    DataWatchRegistration<br>    ExistsWatchRegistration<br><br>ClientCnxn<br>Packet<br></code></pre></td></tr></table></figure>

<h2 id="Watcher接口"><a href="#Watcher接口" class="headerlink" title="Watcher接口"></a>Watcher接口</h2><p>Watcher 接口中包含:<br>1.Event 接口,用于定义<code>事件所代表的状态</code><br>Event 接口中包含 KeeperState(<code>事件发生时zk的状态</code>) 和 EventType(事件类型)两个枚举类<br>2.process() 抽象方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> org.apache.zookeeper;<br><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title class_">Watcher</span> &#123;<br>    <span class="hljs-comment">/** </span><br><span class="hljs-comment">    * 表示事件</span><br><span class="hljs-comment">    */</span><br>    <span class="hljs-meta">@InterfaceAudience</span>.Public<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title class_">Event</span> &#123;<br><br>        <span class="hljs-comment">/** </span><br><span class="hljs-comment">        * 事件发生时Zookeeper的状态</span><br><span class="hljs-comment">        */</span><br>        <span class="hljs-meta">@InterfaceAudience</span>.Public<br>        <span class="hljs-keyword">public</span> <span class="hljs-keyword">enum</span> <span class="hljs-title class_">KeeperState</span> &#123;<br>            <span class="hljs-meta">@Deprecated</span><br>            Unknown(-<span class="hljs-number">1</span>),<span class="hljs-comment">// 未知状态.不再使用,服务器不会产生此状态</span><br><br>            Disconnected(<span class="hljs-number">0</span>),<span class="hljs-comment">// 断开</span><br><br>            <span class="hljs-meta">@Deprecated</span><br>            NoSyncConnected(<span class="hljs-number">1</span>),<span class="hljs-comment">// 未同步连接.不再使用,服务器不会产生此状态</span><br><br>            SyncConnected(<span class="hljs-number">3</span>),<span class="hljs-comment">// 同步连接状态</span><br><br>            AuthFailed(<span class="hljs-number">4</span>),<span class="hljs-comment">// 认证失败状态</span><br><br>            ConnectedReadOnly(<span class="hljs-number">5</span>),<span class="hljs-comment">// 只读连接状态</span><br><br>            SaslAuthenticated(<span class="hljs-number">6</span>),<span class="hljs-comment">// SASL认证通过状态</span><br><br>            Expired(-<span class="hljs-number">112</span>);<span class="hljs-comment">// 过期状态</span><br>            <span class="hljs-comment">// ...</span><br>        &#125;<br><br>        <span class="hljs-comment">/** </span><br><span class="hljs-comment">        * 事件类型</span><br><span class="hljs-comment">        */</span><br>        <span class="hljs-keyword">public</span> <span class="hljs-keyword">enum</span> <span class="hljs-title class_">EventType</span> &#123;<br>            None(-<span class="hljs-number">1</span>),<span class="hljs-comment">// 无</span><br>            NodeCreated(<span class="hljs-number">1</span>),<span class="hljs-comment">// 节点创建</span><br>            NodeDeleted(<span class="hljs-number">2</span>),<span class="hljs-comment">// 节点删除</span><br>            NodeDataChanged(<span class="hljs-number">3</span>),<span class="hljs-comment">// 节点数据变化</span><br>            NodeChildrenChanged(<span class="hljs-number">4</span>);<span class="hljs-comment">// 节点的子节点变化</span><br>        &#125;<br>    &#125;<br><br>    <span class="hljs-comment">// process()方法</span><br>    <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">process</span><span class="hljs-params">(WatchedEvent event)</span>;<br>&#125;<br><br></code></pre></td></tr></table></figure>
<h2 id="回调方法-process"><a href="#回调方法-process" class="headerlink" title="回调方法 process()"></a>回调方法 process()</h2><p>zk server 向 client 发送一个 watcher 通知时,会回调对应的 process() 方法.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">abstract</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">process</span><span class="hljs-params">(WatchedEvent event)</span>;<br></code></pre></td></tr></table></figure>

<h2 id="WatchedEvent"><a href="#WatchedEvent" class="headerlink" title="WatchedEvent"></a>WatchedEvent</h2><p>process()方法的参数 WatchedEvent,zk server会将watcher事件通过 WatchedEvent 对象 传递给 client,WatchedEvent 包含了事件的一些属性:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java">WatchedEvent属性<br>-keeperState: KeeperState <span class="hljs-comment">// 通知状态</span><br>-eventType: EventType <span class="hljs-comment">// 事件类型</span><br>-path: String <span class="hljs-comment">// 对应的path</span><br></code></pre></td></tr></table></figure>

<h2 id="WatcherEvent"><a href="#WatcherEvent" class="headerlink" title="WatcherEvent"></a>WatcherEvent</h2><p>WatcherEvent 用于网络传输.</p>
<p>zk server 在生成 WatchedEvent 事件后,通过 getwrapper() 将 WatchedEvent 包装成 可序列化的 WatcherEvent事件,用于网络传输.</p>
<p>zk client 接收到 server 的 WatcherEvent 对象后,会将 WatcherEvent 反序列化成 WatchedEvent 事件,传给 process() 方法.</p>
<h2 id="ServerCnxn"><a href="#ServerCnxn" class="headerlink" title="ServerCnxn"></a>ServerCnxn</h2><p>ServerCnxn 实现了 Watcher 接口</p>
<h2 id="WatchManager"><a href="#WatchManager" class="headerlink" title="WatchManager"></a>WatchManager</h2><p>WatchManager 是 ZooKeeper 服务端 Watcher 的管理者,包含 watchTable 和 watch2Paths.</p>
<link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/markmap-toolbar@0.18.10/dist/style.css"><script src="https://fastly.jsdelivr.net/npm/d3@7"></script><script src="https://fastly.jsdelivr.net/npm/markmap-view@0.18.10"></script><script src="https://fastly.jsdelivr.net/npm/markmap-toolbar@0.18.10"></script>
<link rel="stylesheet" href="/css/markmap.css">

<script src="/js/markmap.js"></script>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="https://flyingzc.github.io">flyingzc</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="https://flyingzc.github.io/articles/zk/zk08_watcher.html">https://flyingzc.github.io/articles/zk/zk08_watcher.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来源 <a href="https://flyingzc.github.io" target="_blank">flyingzc's blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Zookeeper/">Zookeeper</a></div><div class="post-share"><div class="social-share" data-image="/images/zc-icon.jpeg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><a class="pagination-related" href="/articles/zk/zk01_build.html" title="Zookeeper环境搭建"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2019-01-17</div><div class="info-item-2">Zookeeper环境搭建</div></div><div class="info-2"><div class="info-item-1">zk idea 代码阅读环境搭建采用最新的 zookeeper release 版本 3.4.13zk发行版下载地址 从 github 上 clone 该版本的代码. 1. ant 构建 zkbuild.xml 搜索 ant-eclipse-1.0.bin.tar.bz2, 1290行修改 12&lt;get src=&quot;http://ufpr.dl.sourceforge.net/project/ant-eclipse/ant-eclipse/1.0/ant-eclipse-1.0.bin.tar.bz2&quot;dest=&quot;$&#123;src.dir&#125;/java/ant-eclipse-1.0.bin.tar.bz2&quot; usetimestamp=&quot;false&quot; /&gt; 执行 ant eclipse 2. idea 导入这个 eclipse 项目即可File -&gt; New -&gt; import project from exist source -&gt; 选eclipse 将...</div></div></div></a><a class="pagination-related" href="/articles/zk/zk02_start.html" title="Zookeeper启动流程"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2019-01-18</div><div class="info-item-2">Zookeeper启动流程</div></div><div class="info-2"><div class="info-item-1">zk启动流程 启动类为 QuorumPeerMain 解析 zoo.cfg 配置 创建并启动 DatadirCleanupManager 用于清理过期 snapshot 和 txnlog. 创建 QuorumPeer 实例并启动该线程,用于完成选举. 根据 snapshot 和 txnlog 恢复 内存数据库 ZKDatabase.  12345678910111213141516171819202122232425262728293031323334353637383940- QuorumPeerMain.main()- 1.创建QuorumPeerMain对象- 2.初始化 运行 main.initializeAndRun(args)    - 0.创建QuorumPeerConfig对象    - 1.通过QuorumPeerConfig.parse(),解析配置文件         - 读取zoo.cfg配置到Properties中        - parseProperties()解析Properties配置到QuorumPeerConfig对象中    -...</div></div></div></a><a class="pagination-related" href="/articles/zk/zk03_vote.html" title="Zookeeper选举流程"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2019-02-18</div><div class="info-item-2">Zookeeper选举流程</div></div><div class="info-2"><div class="info-item-1">leader选举相关线程QuorumCnxManager : 管理者,包含发送 和 接收 队列.持有 listener. QuorumCnxManager.Listener : 监听 并 建立 server 之间的连接. FastLeaderElection.Messenger.SendWorker消息生产者.循环 从发送队列 queueSendMap 中取消息(出队)并发送出去.并将该消息存入 lastMessageSent 中. FastLeaderElection.Messenger.RecvWorker消息消费者.循环 接收线程从底层 Socket 收到报文后放到 recvQueue 队列中,等待 Messenger 调用 pollRecvQueue 方法获取消息. leader选举流程启动时选举选举算法的创建之前先创建 QuorumCnxManager,它通过 TCP 协议来进行 leader...</div></div></div></a><a class="pagination-related" href="/articles/zk/zk04_sync.html" title="Zookeeper数据同步流程"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2019-01-17</div><div class="info-item-2">Zookeeper数据同步流程</div></div><div class="info-2"><div class="info-item-1">zk选举完后数据同步流程Leader为每个Follower&#x2F;observer都建立一个TCP长连接. LearnerHandler,即learner服务器的管理者,负责follower&#x2F;observer服务器和leader服务器之间的一系列网络通信.包括数据同步,请求转发和Proposal提议的投票等. leader.lead();-&gt;leader 从磁盘中恢复数据和session列表Leader zk.loadData();-&gt;Leader 启动监听线程 LearnerCnxAcceptor, 等待新的followers的连接请求-&gt;follower 连接leaderFollower follower.followLeader();-&gt;LearnerCnxAcceptor 监听到follower的socket请求,为每个 follower 创建单独的 LearnerHandler 线程用于交互.-&gt;follower 发送 FOLLOWERINFO 包 给leader,包括新的zxid​和 sidFollower...</div></div></div></a><a class="pagination-related" href="/articles/zk/zk05_processor.html" title="Zookeeper Processor"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2019-03-08</div><div class="info-item-2">Zookeeper Processor</div></div><div class="info-2"><div class="info-item-1">processors PrepRequestProcessor通常是请求处理链的第一个处理器.识别客户端请求是否是事务请求.对于事务请求,做预处理,诸如 创建请求事务头,事务体,会话检查,ACL检查 和 版本检查 等.  ProposalRequestProcessorleader 服务器的事务投票处理器,也是 leader 服务器事务处理流程的发起者.对于 非事务请求,它会直接将请求流转到 CommitProcessor 处理器,不再做其他处理.对于 事务请求,除了将请求交给CommitProcessor处理器外,还会根据请求类型创建对应的 Proposal 提议,并 发给所有 Follower 来发起一次集群内的事务投票.它还会将事务请求交给 SyncRequestProcessor 进行事务日志的记录.  SyncRequestProcessor事务日志记录处理器,将事务请求记录到事务日志文件中,同时还会触发zk进行数据快照.发送Sync请求的处理器.将请求记录到磁盘.它批量处理有效执行io的请求.在将日志同步到磁盘之前,请求不会传递到下一个...</div></div></div></a><a class="pagination-related" href="/articles/zk/zk06_snapshot_txnlog.html" title="Zookeeper事务日志，快照"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2019-05-07</div><div class="info-item-2">Zookeeper事务日志，快照</div></div><div class="info-2"><div class="info-item-1">ZKDataBase结构ZKDataBase(zk内存数据库)    – sessionWithTimeouts(zk所有会话  会话超时时间记录器)    – DataTree存储    – 事务日志 ZKDatabase会定时向磁盘dump快照数据,在zk启动时通过磁盘上的事务日志 和 快照文件 恢复 一个完整的内存数据库 事务日志dataLogDir 文件大小都是64MB 文件名 log.xxxxxx为事务id : zxid, 且 为写入该事务文件第一条事务记录的zxid. zxid由两部分组成: 高32位 为 当前leader周期(epoch), 低32位 为 真正的操作序列号. LogFormatter 可以查看该文件 事务日志操作 滚动日志FileTxnLog.rollLog()将当前日志文件 滚动为新文件.其实就是将 logStream置为null,那么要写入日志时就会新创建一个日志文件用于写入.  写事务日志FileTxnLog.append(TxnHeader hdr, Record txn)   若logStream &#x3D;&#x3D; null,...</div></div></div></a></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info text-center"><div class="avatar-img"><img src="/images/zc-icon.jpeg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info-name">flyingzc</div><div class="author-info-description">不积跬步无以至千里<br/>不积小流无以成江海</div><div class="site-data"><a href="/archives/"><div class="headline">文章</div><div class="length-num">84</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">36</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">29</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/FlyingZC"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons"><a class="social-icon" href="https://github.com/FlyingZC" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">FlyingZC's Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#watcher%E6%B5%81%E7%A8%8B"><span class="toc-number">1.</span> <span class="toc-text">watcher流程</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#client-%E6%B3%A8%E5%86%8C-Watcher"><span class="toc-number">1.1.</span> <span class="toc-text">client 注册 Watcher</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#server-%E5%A4%84%E7%90%86-Watcher"><span class="toc-number">1.2.</span> <span class="toc-text">server 处理 Watcher</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#client-%E5%9B%9E%E8%B0%83-Watcher"><span class="toc-number">1.3.</span> <span class="toc-text">client 回调 Watcher</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%9B%B8%E5%85%B3%E7%B1%BB"><span class="toc-number">2.</span> <span class="toc-text">相关类</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Watcher%E6%8E%A5%E5%8F%A3"><span class="toc-number">2.1.</span> <span class="toc-text">Watcher接口</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9B%9E%E8%B0%83%E6%96%B9%E6%B3%95-process"><span class="toc-number">2.2.</span> <span class="toc-text">回调方法 process()</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#WatchedEvent"><span class="toc-number">2.3.</span> <span class="toc-text">WatchedEvent</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#WatcherEvent"><span class="toc-number">2.4.</span> <span class="toc-text">WatcherEvent</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#ServerCnxn"><span class="toc-number">2.5.</span> <span class="toc-text">ServerCnxn</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#WatchManager"><span class="toc-number">2.6.</span> <span class="toc-text">WatchManager</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite03-transaction-begin.html" title="Apache Ignite 开启事务执行流程">Apache Ignite 开启事务执行流程</a><time datetime="2025-10-10T16:00:00.000Z" title="发表于 2025-10-11 00:00:00">2025-10-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite02-transaction.html" title="Apache Ignite 分布式事务原理">Apache Ignite 分布式事务原理</a><time datetime="2025-09-17T16:00:00.000Z" title="发表于 2025-09-18 00:00:00">2025-09-18</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite01-build.html" title="Apache Ignite IDEA 环境搭建">Apache Ignite IDEA 环境搭建</a><time datetime="2025-09-10T16:00:00.000Z" title="发表于 2025-09-11 00:00:00">2025-09-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/druid/druid01-resultset-leak.html" title="ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析">ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析</a><time datetime="2025-06-30T16:00:00.000Z" title="发表于 2025-07-01 00:00:00">2025-07-01</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/jmeter/jmeter01-shardingsphere.html" title="Jmeter 压测 ShardingSphere">Jmeter 压测 ShardingSphere</a><time datetime="2025-06-30T16:00:00.000Z" title="发表于 2025-07-01 00:00:00">2025-07-01</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2025 By flyingzc</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="日间和夜间模式切换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>